package org.example.service.oaa;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.example.dao.dao.market.CBusinessDao;
import org.example.dao.dto.market.BusinessDto;
import org.example.dao.entity.market.CBusiness;
import org.example.exception.AuthException;
import org.example.skytool.commom.ContextUtil;
import org.example.skytool.security.EncodeUtil;
import org.example.skytool.security.JwtUtils;
import org.example.utils.market.Store.RedisStoreService;
import org.example.utils.oaa.RedisBusinessService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

/**
 * @author xluo
 * @date 2023/10/30 11:18
 */
@Service
public class LoginService {

    @Resource
    private CBusinessDao cBusinessDao;

    @Resource
    private RedisBusinessService redisBusinessService;

    @Resource
    private RedisStoreService redisStoreService;

    @Resource
    private ContextUtil contextUtil;

    public String login(String username, String password) {
        LambdaQueryWrapper<CBusiness> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CBusiness::getIsValid, 1);
        lambdaQueryWrapper.eq(CBusiness::getUsername, username);
        CBusiness business = cBusinessDao.selectOne(lambdaQueryWrapper);
        if (business != null && EncodeUtil.match(password, business.getPassword())) {
            Long id = business.getId();
            String token = JwtUtils.getJwtToken(id.toString(), "null");
            business.setLastLoginTime(new Date());
            cBusinessDao.updateById(business);
            redisBusinessService.setCacheToken(id.toString(), token);

            BusinessDto businessDto = cBusinessDao.selectBusinessDto(id);

//            redisBusinessService.setBusinessDto(businessDto);
            redisBusinessService.setCachePermission(businessDto);
            redisStoreService.setCacheStoreIds(id);

            return token;
        } else {
            throw new AuthException("密码错误或用户不可用");
        }
    }

    public String verify(String token) {
        return token;
    }

}
